---
title: Svelte Examples
description: Learn how to test Svelte components with Cypress Component Testing.
sidebar_position: 30
sidebar_label: Examples
---

<ProductHeading product="app" />

# Svelte Examples

:::info

##### <Icon name="question-circle" color="#4BBFD2" /> What you'll learn

- How to mount a Svelte component
- How to pass props to a Svelte component
- How to test event handlers in a Svelte component
- How to access the component instance in a test

:::

## Mounting Components

### Using `cy.mount()`

To mount a component with `cy.mount()`, import the component and pass it to the
method:

```ts
import { Stepper } from './stepper.svelte'

it('mounts', () => {
  cy.mount(Stepper)
})
```

### Passing Data to a Component

You can pass props to a component by setting props in the options: `cy.mount()`:

```ts
it('mounts', () => {
  cy.mount(Stepper, { props: { count: 100 } })
})
```

### Testing Event Handlers

To test emitted events from a Svelte component, we need to pass in a callback
for when we increment the stepper. The Stepper component
will need to invoke this callback for us. We can also pass in a
Cypress spy so we can query the spy later for results. In the example below, we
pass in the `onChange` callback handler and validate it was called as expected:

```js
it('clicking + fires a change event with the incremented value', () => {
  const onChangeSpy = cy.spy().as('onChangeSpy')
  cy.mount(Stepper, { props: { onChange: onChangeSpy } })
  cy.get('[data-cy=increment]').click()
  cy.get('@onChangeSpy').should('have.been.calledWith', 1)
})
```

### Accessing the Component Instance

There might be times when you might want to access the component instance
directly in your tests. To do so, use `.then()`, which enables us to work with
the subject that was yielded from the `cy.mount()` command.

```js
cy.mount(Stepper).then(({ component }) => {
  //component is the rendered instance of Stepper
})
```
